package site.xuxingcan.messageclient;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;
import java.net.Socket;
import java.security.MessageDigest;
import java.util.List;

public class MainActivity extends Activity {
    private Handler mHandler;
    private Button mLoginInButton;
    private EditText mIpEditText;
    private EditText mPortEditText;
    private EditText mMessageEditText;
    private Button messageActivityButton;
    private EditText loginNameEditText;
    private EditText loginPwdEditText;
    private Button mLoginOutButton;
    private Socket socket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandler = new Handler();
        mLoginInButton = (Button) findViewById(R.id.login_in_button);
        mLoginOutButton = (Button) findViewById(R.id.login_out_button);
        messageActivityButton = (Button) findViewById(R.id.message_activity);
        mIpEditText = (EditText) findViewById(R.id.ip);
        if (SharedPreferenceUtil.getInstance(this).getIp() != null) {
            mIpEditText.setText(SharedPreferenceUtil.getInstance(this).getIp());
        }
        mPortEditText = (EditText) findViewById(R.id.port);
        if (SharedPreferenceUtil.getInstance(this).getPort() != null) {
            mPortEditText.setText(SharedPreferenceUtil.getInstance(this).getPort());
        }
        loginNameEditText = (EditText) findViewById(R.id.login_name);
        if (SharedPreferenceUtil.getInstance(this).getName() != null) {
            loginNameEditText.setText(SharedPreferenceUtil.getInstance(this).getName());
        }
        loginPwdEditText = (EditText) findViewById(R.id.login_pwd);
        if (SharedPreferenceUtil.getInstance(this).getPWD() != null) {
            loginPwdEditText.setText(SharedPreferenceUtil.getInstance(this).getPWD());
        }
        mMessageEditText = (EditText) findViewById(R.id.message);
        if (SharedPreferenceUtil.getInstance(this).getMessage() != null) {
            mMessageEditText.setText(SharedPreferenceUtil.getInstance(this).getMessage());
        }
        messageActivityButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, MessageActivity.class));
            }
        });
        mLoginInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferenceUtil.getInstance(MainActivity.this).setIp(mIpEditText.getText().toString());
                SharedPreferenceUtil.getInstance(MainActivity.this).setPort(mPortEditText.getText().toString());
                SharedPreferenceUtil.getInstance(MainActivity.this).setName(loginNameEditText.getText().toString());
                SharedPreferenceUtil.getInstance(MainActivity.this).setPWD(loginPwdEditText.getText().toString());
                SharedPreferenceUtil.getInstance(MainActivity.this).setMessage(mMessageEditText.getText().toString());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    mLoginInButton.setText("登录中......");
                                    mLoginInButton.setEnabled(false);
                                    mLoginOutButton.setEnabled(true);
                                    mIpEditText.setEnabled(false);
                                    mPortEditText.setEnabled(false);
                                    mMessageEditText.setEnabled(false);
                                    loginPwdEditText.setEnabled(false);
                                    loginNameEditText.setEnabled(false);
                                }
                            });
                            String message = mMessageEditText.getText().toString();
                            socket = new Socket(mIpEditText.getText().toString(), Integer.parseInt(mPortEditText.getText().toString()));
                            socket.setKeepAlive(true);
//                            socket.setSoTimeout(6 * 60 * 1000);
                            socket.setSoTimeout(0);
                            SocketHelper socketHelper = new SocketHelper(socket);
                            //登录
                            socketHelper.writeLineAndFlush(loginNameEditText.getText().toString() + "#" + string2MD5LowerCase(loginPwdEditText.getText().toString()));
                            String s = socketHelper.readLine();
                            if (!s.equalsIgnoreCase("LOGIN_SUCCESS")) {
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this, "登录失败，请检查用户名和密码！", Toast.LENGTH_LONG).show();
                                    }
                                });
                                socketHelper.close();
                                throw new Exception("LOGIN_FAILED");
                            } else {
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this, "登录成功，开始监听短信请求！", Toast.LENGTH_LONG).show();
                                        mLoginInButton.setText("消息监听中......");
                                        mLoginInButton.setEnabled(false);
                                        mLoginOutButton.setEnabled(true);
                                        mIpEditText.setEnabled(false);
                                        mPortEditText.setEnabled(false);
                                        mMessageEditText.setEnabled(false);
                                        loginPwdEditText.setEnabled(false);
                                        loginNameEditText.setEnabled(false);
                                    }
                                });
                            }
                            //监听
                            while (true) {
                                s = socketHelper.readLine();
                                if (s == null) {
                                    throw new Exception("null");
                                }
                                Log.i("xuxingcan", s);
                                if (s.equalsIgnoreCase("PING")) {
                                    socketHelper.writeLineAndFlush("PING_OK");
                                } else {
                                    final String[] strings = s.split("#");
                                    if (strings.length == 2) {
                                        sendSMS(strings[0], String.format(message, strings[1]));
                                        FileUtil.getInstance(MainActivity.this).addMessage(new MessageModel(System.currentTimeMillis(), strings[0], strings[1]));
                                    }
                                    socketHelper.writeLineAndFlush("RECEIVED");
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    mLoginInButton.setText("点击登录");
                                    mLoginInButton.setEnabled(true);
                                    mLoginOutButton.setEnabled(false);
                                    mIpEditText.setEnabled(true);
                                    mPortEditText.setEnabled(true);
                                    mMessageEditText.setEnabled(true);
                                    loginPwdEditText.setEnabled(true);
                                    loginNameEditText.setEnabled(true);
                                }
                            });
                        }
                    }
                }).start();
            }
        });
        mLoginOutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private static String string2MD5LowerCase(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toLowerCase();
    }

    /**
     * 直接调用短信接口发短信
     *
     * @param phoneNumber
     * @param message
     */
    public void sendSMS(final String phoneNumber, final String message) {
        //获取短信管理器
//        mHandler.post(new Runnable() {
//            @Override
//            public void run() {
//                Toast.makeText(MainActivity.this, phoneNumber + "\n" + message, Toast.LENGTH_LONG).show();
//            }
//        });
        android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
        //拆分短信内容（手机短信长度限制）
        List<String> divideContents = smsManager.divideMessage(message);
        for (String text : divideContents) {
            smsManager.sendTextMessage(phoneNumber, null, text, null, null);
        }
    }
}
